<template>
  <div class="comments-container">
    <div class="main-card">
      <!-- 页面标题 -->
      <div class="card-header">
        <h2 class="card-title">评论管理</h2>
      </div>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-container">
          <div class="search-item">
            <span class="search-label">内容关键词</span>
            <el-input v-model="queryParams.content" placeholder="请输入评论内容关键词" clearable @keyup.enter="handleQuery"
              class="search-input">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="search-buttons">
            <el-button type="primary" @click="handleQuery" :icon="Search">查询</el-button>
            <el-button @click="resetQuery" :icon="RefreshRight">重置</el-button>
          </div>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table :data="tableData" fit v-loading="loading" border stripe highlight-current-row
          :cell-style="{ textAlign: 'center' }">
          <el-table-column prop="id" label="ID" align="center" />
          <el-table-column prop="content" label="评论内容" align="center">
            <template #default="{ row }">
              <div class="comment-content">
                <el-popover
                  placement="top"
                  :width="400"
                  trigger="hover"
                  v-if="row.content"
                >
                  <template #reference>
                    <el-tag
                      type="info"
                      effect="plain"
                      class="content-tag"
                    >
                      {{ truncateText(row.content, 30) }}
                    </el-tag>
                  </template>
                  <div class="content-popover">
                    <div class="content-title">评论内容</div>
                    <div class="content-text">{{ row.content }}</div>
                  </div>
                </el-popover>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="likeCount" label="点赞数" align="center" />
          <el-table-column label="状态" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isDeleted ? 'danger' : 'success'">
                {{ row.isDeleted ? '已删除' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="创建时间" align="center" />
          <el-table-column prop="updatedTime" label="更新时间" align="center" />
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="{ row }">
              <el-button 
                v-if="!row.isDeleted" 
                type="danger" 
                link 
                @click="handleDelete(row)" 
                class="action-button"
              >
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
              <span v-else class="deleted-text">已删除</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { debounce } from 'lodash-es'
import { Search, RefreshRight, Delete } from '@element-plus/icons-vue'
import { getCommentsPageList, deleteCommentsById } from '@/api/comments'

// 查询参数
const queryParams = reactive({
  content: '',
  pageNum: 1,
  pageSize: 10
})

// 数据列表
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 文本截断函数
const truncateText = (text, length) => {
  if (!text) return '';
  return text.length > length ? text.substring(0, length) + '...' : text;
}

// 防抖处理查询
const debouncedQuery = debounce(() => {
  getList()
}, 300)

// 获取评论列表
const getList = async () => {
  if (loading.value) return
  loading.value = true
  try {
    const params = {
      content: queryParams.content,
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    }
    const res = await getCommentsPageList(params)
    if (res.code === 200) {
      tableData.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error({
        message: res.msg || '获取评论列表失败',
        duration: 3000,
        showClose: true
      })
    }
  } catch (error) {
    console.error('获取评论列表出错:', error)
    if (!error.code || error.code !== 403) {
      ElMessage.error({
        message: '获取评论列表出错，请稍后重试',
        duration: 3000,
        showClose: true
      })
    }
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  debouncedQuery()
}

// 重置按钮
const resetQuery = () => {
  queryParams.content = ''
  handleQuery()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  debouncedQuery()
}

// 页码变化
const handleCurrentChange = (current) => {
  queryParams.pageNum = current
  debouncedQuery()
}

// 删除评论
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除这条评论吗？此操作不可逆。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 同步删除操作
    deleteCommentsById(row.id)
      .then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getList() // 刷新列表
        } else {
          ElMessage.error(res.msg || '删除失败')
        }
      })
      .catch(error => {
        if (!error.code || error.code !== 403) {
          ElMessage.error('删除失败，请稍后重试')
        }
      })
  }).catch(() => {
    // 用户取消操作
  })
}

// 页面加载时初始化数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.comments-container {
  padding: 20px;
}

.main-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  padding: 20px;
}

.card-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
}

.card-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  font-weight: 500;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  min-width: 200px;
}

.search-label {
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.search-input {
  width: 100%;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-left: auto;
  align-self: flex-end;
}

.table-section {
  margin-top: 16px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.action-button {
  margin-right: 8px;
}

.comment-content {
  max-width: 100%;
  display: flex;
  justify-content: center;
}

.content-tag {
  max-width: 100%;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
  padding: 5px 12px;
}

.content-popover {
  max-height: 300px;
  overflow-y: auto;
}

.content-title {
  font-weight: bold;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
  color: #303133;
}

.content-text {
  color: #606266;
  line-height: 1.5;
  word-break: break-word;
  white-space: pre-wrap;
}

.deleted-text {
  color: #909399;
  font-size: 13px;
  font-style: italic;
}
</style>